package ru.ifmo.swing.genetics.termination;

import org.uncommons.watchmaker.framework.PopulationData;
import org.uncommons.watchmaker.framework.TerminationCondition;
import ru.ifmo.swing.ProgressStartListener;
import ru.ifmo.swing.genetics.ProcessFinishedListener;

import java.awt.*;
import java.util.List;

/**
 * @author avhaliullin
 */
public class ComponentsDisabler implements TerminationCondition, ProgressStartListener {
    private final TerminationCondition terminationCondition;
    private final List<Component> disableList;
    private final List<Component> enableList;

    private final List<ProcessFinishedListener> processFinishedListeners;

    public ComponentsDisabler(TerminationCondition terminationCondition, List<Component> disableList,
                              List<Component> enableList, List<ProcessFinishedListener> processFinishedListeners) {
        this.terminationCondition = terminationCondition;
        this.disableList = disableList;
        this.enableList = enableList;
        this.processFinishedListeners = processFinishedListeners;
    }

    private void disable(boolean disable) {
        for (Component component : disableList) {
            component.setEnabled(!disable);
        }
        for (Component component : enableList) {
            component.setEnabled(disable);
        }

    }

    public void progressStarted() {
        disable(true);
    }

    public boolean shouldTerminate(PopulationData<?> populationData) {
        if (terminationCondition.shouldTerminate(populationData)) {
            disable(false);
            for (ProcessFinishedListener listener : processFinishedListeners) {
                listener.finished();
            }
            return true;
        }
        return false;
    }
}
